<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example3(Shooting): HTML5 canvas</title>
</head>
<body>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
	var w_size = 720;
	var h_size = 500;
	var oval_size = 10;
	var mouse_X = 0;
	var mouse_Y = 0;

	// 敵の移動速度(値が大きいほど遅い)
	var enemy_timer = 7;
	// 弾の移動速度(値が小さいほど遅い)
	var bullet_timer = 5;

	// 開始時間
	var start_time = 0;
	// 敵のx軸の間隔
	var x_span = [10, 45, 80, 115, 150, 185, 220];
	// 敵のy軸の間隔
	var y_span = [0, 30, 60, 90];
	// 敵の総数
	var total_enemy_count = x_span.length * y_span.length;
	
	// 敵の点数
	var enemy_score = [40, 30, 20, 10];
	// 敵の色
	var enemy_color = ["#ff0000", "#c00080", "#00ff00","000000"];

	var moveCount = 0;

	// 弾
	var bullect_count = 0;
	var bullect_u = 1;
	var bullet_array = [];


	$(function() {

		// 総合点
		var total = 0;
		// 得点描画
		var dispScore = function(score) {
			total += score;
			document.getElementById('score').innerHTML = "SCORE: " + total;
		};
			
		// 描画リセット
		var reset = function(ctx) {
				ctx.clearRect(0,0,w_size,h_size);
				ctx.strokeStyle = "black";
				// 枠
				ctx.strokeRect(0,0,w_size,h_size);
				// 敵との境界
				ctx.moveTo(0, h_size - 100);
				ctx.lineTo(w_size, h_size - 100);
				ctx.stroke();
		};
		
		// 結果表示
		var result = function(ctx, message) {
			reset(ctx);
			ctx.font = "50px 'ＭＳ Ｐゴシック'";
			ctx.fillStyle = "red";
			ctx.fillText(message, 200, 200);
		};

		// 初期描画
		var startEnemy = function() {
			dispScore(0);
			var canvas =  document.getElementById('canvassample');
			/* canvas要素の存在チェックとCanvas未対応ブラウザの対処 */
			if ( ! canvas || ! canvas.getContext ) {
				document.getElementById('ms').innerHTML = "This browser is not supported.";	
				return false;
			}
			/* 2Dコンテキスト */
			var ctx = canvas.getContext('2d');
			reset(ctx);

			for (var i = 0; i < y_span.length; i++) {
				enemyLineDraw(ctx, moveCount, y_span[i], i);
			}
		};


		//敵作成
		//7 x 4マスのどこに敵がいるか？
		// 全てに敵がいるように初期化
		function Teki(){};
		var enemy_exist;
		var createEnemy = function() {
			enemy_exist = new Array(7);
			for (var i = 0; i < enemy_exist.length; i++) {
				var tmp = new Array(4);
				for (var j = 0; j < tmp.length; j++) {
					var teki = new Teki();
					teki.exist = 1;
					teki.x = 0;
					teki.y = 0;
					teki.score = enemy_score[j];
					tmp[j] = teki;
				}
				enemy_exist[i] = tmp;
			}
		};

		// 左→右移動
		var rightMove = function(ctx, x_move, y_move, y_pos) {

			for (var i = 0; i < x_span.length; i++) {
				var posX = (x_move % h_size) + x_span[i];
				var posY = y_move + 50;
				enemy_exist[i][y_pos].x = posX;
				enemy_exist[i][y_pos].y = posY;
				if (enemy_exist[i][y_pos].exist == 1) {
					ctx.beginPath();
					ctx.arc(posX, posY, oval_size, 0, Math.PI*2, false);
					ctx.fill();
					if (checkEnd(posY)) {
						clearInterval(id);
						result(ctx, "GAME OVER");
						break;
					}
				}
			}
		};

		// 右→左移動 
		var leftMove = function(ctx, x_move, y_move, y_pos) {

			for (var i =  0; i < x_span.length; i++) {
				var posY = y_move + 50;
				var posX = enemy_exist[i][y_pos].x - 1;
				enemy_exist[i][y_pos].x = posX;
				enemy_exist[i][y_pos].y = posY;
				if (enemy_exist[i][y_pos].exist ==1) {
					ctx.beginPath();
					ctx.arc(posX, posY, oval_size, 0, Math.PI*2, false);
					ctx.fill();
					if (checkEnd(posY)) {
						clearInterval(id);
						result(ctx, "GAME OVER");
						break;
					}
				} 
			}
		};

		// ゲームオーバー判定
		var checkEnd = function(posY) {
			if (posY + oval_size > 400) {
				return true;
			}
			return false;
		};

		var right = false;
		var change_count = 0;
		var y_move_count = 0;
		// 敵を動かす。左右どちらに動かすかの制御を行なう
		var enemyLineDraw = function(ctx, x_move, y_move, count) {

			ctx.fillStyle = enemy_color[count];
			// x軸変更
			if (x_move % h_size == 0) {
				if (change_count != x_move) {
					right = !right;
					change_count = x_move;
					y_move_count++;
				}
			} 

			if (right) {
				leftMove(ctx, x_move, y_move + y_move_count * 30, count);
			} else {
				rightMove(ctx, x_move, y_move + y_move_count * 30, count);
			}
		};

		createEnemy();
		startEnemy();

		// 当たり判定
		var hitCheck = function() {
			if (bullet_array.length == 0) {
				return;
			}
			var bullet_pos = bullet_array[0];
			var hitFlg = false;
			for (var i = 0; i < enemy_exist.length; i++) {
				// 敵の存在確認が必要
				for (var j = 0; j < 4; j++) {
					if (enemy_exist[i][j].x - oval_size <= bullet_pos[0] && enemy_exist[i][j].x + oval_size >= bullet_pos[0] &&
						enemy_exist[i][j].y - oval_size <= bullet_pos[1] && enemy_exist[i][j].y + oval_size >= bullet_pos[1] &&
						enemy_exist[i][j].exist == 1) {
						bullet_array = [];
						enemy_exist[i][j].exist = 0;
						hitFlg = true;
						dispScore(enemy_exist[i][j].score);
						total_enemy_count--;
						break;
					}
				}
				if (hitFlg) {
					break;
				}
			}
		};

		// 弾描画
		var end = 0;
		var bullet = function(ctx) {
			ctx.beginPath();
			ctx.strokeStyle = "#a0410d";
			ctx.lineCap = "round";
			ctx.lineWidth = 1;
			ctx.moveTo(bullet_array[0][0], bullet_array[0][1] - 10);
			ctx.lineTo(bullet_array[0][0], bullet_array[0][1]);
			ctx.stroke();
			if (bullet_array[0][1] >= -5) {
				bullet_array[0][1] -= bullet_timer;
			} else {
				end += 1;
				bullet_array = [];
			}
			
		};

		var id;
		$('#hoge').click(function() {
			function draw() {
				/* canvas要素のノードオブジェクト */
				var canvas = document.getElementById('canvassample');
				/* canvas要素の存在チェックとCanvas未対応ブラウザの対処 */
				if ( ! canvas || ! canvas.getContext ) {
					document.getElementById('ms').innerHTML = "This browser is not supported.";	
					return false;
				}
				/* 2Dコンテキスト */
				var ctx = canvas.getContext('2d');
				reset(ctx);
				
				// クリアー判定
				if (total_enemy_count == 0) {
					clearInterval(id);
					var end_time = new Date();
					var clear_time = Math.floor(end_time.getTime() / 1000) - Math.floor(start_time.getTime() / 1000);
					document.getElementById('clearTime').innerHTML = "CLEAR TIME: " + clear_time + "s";
					result(ctx, "CLEAR");
				}

				// 敵描画
				moveCount++;
				for (var i = 0; i < y_span.length; i++) {
					enemyLineDraw(ctx, moveCount, y_span[i], i);
				}

				// 弾描画
				bullet(ctx);

				// 当たり判定
				hitCheck();
			};
			document.getElementById('hoge').disabled = true;
			start_time = new Date();
			id = setInterval(draw,enemy_timer);
		});
				
		$('#stop').click(function() {
			clearInterval(id);
		});
	});

	// 弾の移動
	function shot() {
		if (bullet_array.length > 0) {
			return;
		}
		var tmp = [];
		tmp[0] = mouse_X -7;
		tmp[1] = mouse_Y - 67;
		bullet_array[0] = tmp;
	};

	function mouseClicked() {
		if (mouse_X > 7 && mouse_X < 728 && mouse_Y > 483 && mouse_Y < 580 ) {
			shot();
		}
	};

	function mouseMove(x, y) {
		mouse_X = x;
		mouse_Y = y;
		document.getElementById("debug").innerHTML = "x = " + x + "   y = " + y;
	};
	</script>
<div id="score"></div>
<div id="clearTime"></div>
<canvas id="canvassample" width="720" height="500" style="position: absolute; top:80px;"
	onmousedown="mouseClicked()"
	onmousemove="mouseMove(event.clientX, event.clientY)">
</canvas>
<div style="position: absolute;top:400px;">.</div>
<form style="position: absolute; top:600px;">
	<input type="button" id="hoge" value="start" />
	<input type="button" id="stop" value="stop" />
	<div id="debug"></div>
</form>
<div id="debug"></div>
</body>
</html>
